package com.qlmjx.sevalopos;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.InputType;
import android.text.LoginFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.deserializer.IntegerFieldDeserializer;
import com.chice.scangun.ScanGun;
import com.qlmjx.sevalopos.Bean.CustomerGoodsBean;
import com.qlmjx.sevalopos.Bean.ManageGoodInfo;
import com.qlmjx.sevalopos.Bean.ManageMemberInfo;
import com.qlmjx.sevalopos.Bean.ManageModleInfo;
import com.qlmjx.sevalopos.Bean.ManageStateInfo;
import com.qlmjx.sevalopos.Bean.MemberBean;
import com.qlmjx.sevalopos.Bean.ModleBean;
import com.qlmjx.sevalopos.Service.HomeService;
import com.qlmjx.sevalopos.View.BaseDialog;
import com.qlmjx.sevalopos.View.ComfirmDialog;
import com.qlmjx.sevalopos.View.ComfirmOrderDialog;
import com.qlmjx.sevalopos.View.ComfirmPayDialog;
import com.qlmjx.sevalopos.View.ShopOrderDialog;
import com.qlmjx.sevalopos.View.SoftKeyboardStateHelper;
import com.qlmjx.sevalopos.View.WareHouseDialog;
import com.qlmjx.sevalopos.View.WattingDialog;
import com.qlmjx.sevalopos.adapter.MemAdapter;
import com.qlmjx.sevalopos.adapter.PopAdapter;
import com.qlmjx.sevalopos.adapter.SaleAdapter;
import com.qlmjx.sevalopos.base.BaseActivity;
import com.qlmjx.sevalopos.base.BaseEvent;
import com.qlmjx.sevalopos.callback.ForCallBack;
import com.qlmjx.sevalopos.event.AdvEvent;
import com.qlmjx.sevalopos.event.CustomerShopEvent;
import com.qlmjx.sevalopos.event.MemEvent;
import com.qlmjx.sevalopos.event.MemIdEvent;
import com.qlmjx.sevalopos.event.PaySEvent;
import com.qlmjx.sevalopos.event.PaystatrEvent;
import com.qlmjx.sevalopos.event.ShopEvent;
import com.qlmjx.sevalopos.event.ZkEvent;
import com.qlmjx.sevalopos.event.ZklEvent;
import com.qlmjx.sevalopos.https.HttpAddress;
import com.qlmjx.sevalopos.https.RequestParams;
import com.qlmjx.sevalopos.utils.ConstantsUtils;
import com.qlmjx.sevalopos.utils.Screensaver;

import com.qlmjx.sevalopos.utils.ViewHolder;
import com.universal.frame.generalutils.Constants;
import com.universal.frame.generalutils.DecimalUtil;
import com.universal.frame.generalutils.GeneralUtil;
import com.universal.frame.generalutils.JsonUtil;
import com.universal.frame.generalutils.LogUtils;
import com.universal.frame.generalutils.SharedPreferencesUtil;
import com.universal.frame.generalutils.ToastUtil;
import com.universal.frame.okhttp.OKHttpUtils;
import com.universal.frame.okhttp.ResultCallBack;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Request;


public class MainActivity extends BaseActivity implements Screensaver.OnTimeOutListener, ResultCallBack, View.OnClickListener, ForCallBack {
    private static final String TAG = "lzx";
    private CustomerActivity presentation;
    private Display[] presentationDisplays;
    private Screensaver mScreensaver;
    private Screensaver SaleScreensaver;
    private EditText ed_shopid;
    private TextView tv_searchmenbr, tv_confirm_all, tv_shop_num, tv_khmc, tv_hyid, tv_zkl, tv_phonecancel,tv_yj, tv_hyj, tv_zzjg, tv_modle, tv_cancel, tv_dj;
    private ListView lv_shop;
    private SaleAdapter saleAdapter;
    private List<CustomerGoodsBean> list = new ArrayList<CustomerGoodsBean>();
    private ComfirmOrderDialog comfirmOrderDialog;
    private WareHouseDialog wareHouseDialog;
    private ScanGun scanGun;
    private int i = 0;
    private TextView tv_total_money;
    private int comfirmtype = 0;
    private Double performancePartDiscount = 0.0;
    private Double commonPartDiscount = 0.0;
    private EditText ed_vipnumber, ed_jh, ed_sq, ed_yhmc;
    private String vipnumber;
    private TextView tv_confirm;
    private ShopOrderDialog shopOrderDialog;
    private String shopid;
    public PopupWindow popupWindow;
    public PopupWindow MempopupWindow;
    public PopupWindow settingpopupWindow;
    private ListView lv_jh;
    private List<ModleBean> poplist = new ArrayList<ModleBean>();
    private List<MemberBean> MemberList = new ArrayList<MemberBean>();
    private PopAdapter popAdapter;
    private RelativeLayout rl_jh, rl_zkl;
    private String jixing;
    private String jihao;
    private int zktype = 0;
    private CheckBox ckb;
    private MemAdapter memAdapter;
    private String saleCustId;
    private ListView lv_hy;
    private String commPartSaleId;
    private ComfirmDialog comfirmDialog;
    private String zhekou;
    private ComfirmDialog outcomfirmDialog;
    private BigDecimal Total_yuanjia;
    private int ischoice = 0;
    private RelativeLayout rl_warehouse, rl_loginout;
    private ImageView iv_settings;
    private TextView tv_list,tv_cy,tv_xn;
    private String partSaleNo;
    private ComfirmPayDialog comfirmPayDialog;
    private String zzjg;
    private WattingDialog wattingDialog;
    private int isphonechoice = 0;
    private LinearLayout ll_hyzk;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

        //不弹出软键
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        scanGun = new ScanGun(new ScanGun.ScanGunCallBack() {
            @Override
            public void onScanFinish(String s) {
                //这里的回调函数的参数s
                //就是扫码枪扫到的那一串字符串
                //TODO 按照你自己的逻辑处理
                Log.i("lzx", "就是扫码枪扫到的那一串字符串: " + s);
                if (!TextUtils.isEmpty(s)) {
                    String MATNR = "";
                    Pattern p = Pattern.compile("[0-9]*");
                    Matcher m = p.matcher(s);
                    if (m.matches()) {
                        return;
                    }
                    try {
                        String uid = getUidFromBase64(s);
                        MATNR = uid.substring(0, uid.indexOf(",")) + "}";
                    } catch (Exception E) {
                        ToastUtil.showToast(getApplicationContext(), E.toString());
                    }
                    String shopid = JsonUtil.getString(MATNR, "MATNR", "");
                    if (!TextUtils.isEmpty(shopid)) {
                        getShopInfo(shopid);
                    } else {
                        ToastUtil.showToast(getApplicationContext(), "扫码过快或者商品暂不存在！");
                    }

                }
            }
        });
        scanGun.setMaxKeysInterval(50);
    }

    @Override
    public void initView() {
        tv_cy= (TextView) findViewById(R.id.tv_cy);
        tv_xn= (TextView) findViewById(R.id.tv_xn);
        rl_zkl = (RelativeLayout) findViewById(R.id.rl_zkl);
        tv_list = (TextView) findViewById(R.id.tv_list);
        ed_shopid = (EditText) findViewById(R.id.ed_shopid);
        tv_searchmenbr = (TextView) findViewById(R.id.tv_searchmenbr);
        tv_confirm = (TextView) findViewById(R.id.tv_confirm);
        tv_confirm_all = (TextView) findViewById(R.id.tv_confirm_all);
        tv_shop_num = (TextView) findViewById(R.id.tv_shop_num);
        tv_total_money = (TextView) findViewById(R.id.tv_total_money);
        ed_vipnumber = (EditText) findViewById(R.id.ed_vipnumber);
        lv_shop = (ListView) findViewById(R.id.lv_shop);
        ed_yhmc = (EditText) findViewById(R.id.ed_yhmc);
        tv_khmc = (TextView) findViewById(R.id.tv_khmc);
        tv_cancel = (TextView) findViewById(R.id.tv_cancel);
        tv_hyid = (TextView) findViewById(R.id.tv_hyid);
        tv_zkl = (TextView) findViewById(R.id.tv_zkl);
        tv_yj = (TextView) findViewById(R.id.tv_yj);
        tv_hyj = (TextView) findViewById(R.id.tv_hyj);
        tv_zzjg = (TextView) findViewById(R.id.tv_zzjg);
        ll_hyzk = (LinearLayout) findViewById(R.id.ll_hyzk);
        tv_phonecancel = (TextView) findViewById(R.id.tv_phonecancel);
//        tv_sq = (TextView) findViewById(R.id.tv_sq);
        iv_settings = (ImageView) findViewById(R.id.iv_settings);
        ed_sq = (EditText) findViewById(R.id.ed_sq);
        ed_jh = (EditText) findViewById(R.id.ed_jh);
        tv_modle = (TextView) findViewById(R.id.tv_modle);
        rl_jh = (RelativeLayout) findViewById(R.id.rl_jh);
        ckb = (CheckBox) findViewById(R.id.ckb);
        tv_dj = (TextView) findViewById(R.id.tv_dj);
        ckb.setChecked(false);
        ed_sq.setEnabled(false);
        ckb.setOnClickListener(this);
        setListenerFotEditText(ed_shopid);
        setListenerFotEditText(ed_vipnumber);
        setListenerFotEditText(ed_sq);
        tv_cancel.setOnClickListener(this);
        iv_settings.setOnClickListener(this);
        tv_list.setOnClickListener(this);
        tv_dj.setOnClickListener(this);
        showwatting();
//        Intent intentService = new Intent(MainActivity.this, HomeService.class);
//        startService(intentService);

        DisplayManager displayManager = (DisplayManager) this.getSystemService(Context.DISPLAY_SERVICE);
        //获取屏幕数量
        presentationDisplays = displayManager.getDisplays();
        if (presentationDisplays.length > 1) {
            presentation = new CustomerActivity(this, presentationDisplays[1]);
            Log.i("lzx", "presentation: " + "presentation1");
        } else {
            presentation = new CustomerActivity(this, presentationDisplays[0]);
            Log.i("lzx", "presentation: " + "presentation2");
        }

        presentation.show();
        mScreensaver = new Screensaver(80000); //定时5秒
        mScreensaver.setOnTimeOutListener(this); //监听
        mScreensaver.start(); //开始计时
        SaleScreensaver = new Screensaver(10000); //定时5秒
        SaleScreensaver.setOnTimeOutListener(new Screensaver.OnTimeOutListener() {
            @Override
            public void onTimeOut(Screensaver screensaver) {
                getStateInfo(commPartSaleId);
            }
        }); //监听
        tv_searchmenbr.setOnClickListener(this);
        tv_confirm_all.setOnClickListener(this);
        tv_confirm.setOnClickListener(this);
        tv_phonecancel.setOnClickListener(this);
//        tv_sq.setOnClickListener(this);

        //给EditText 设置 OnKeyListener
        saleAdapter = new SaleAdapter(this, list, this);
        lv_shop.setAdapter(saleAdapter);
        ed_jh.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 3 && ischoice == 0) {
                    String JH = ed_jh.getText().toString().trim();
                    getModelInfo(JH);
                }
                if (s.length() == 0) {
                    ischoice = 0;
                    tv_modle.setText(null);
                    tv_cancel.setVisibility(View.GONE);
                }
            }
        });
        ed_yhmc.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 3&&isphonechoice ==0) {
                    String phone = ed_yhmc.getText().toString().trim();
                    getMemInfo(phone);
                }
                if (s.length() == 0) {
                    isphonechoice =0;
//                    ed_yhmc.setText(null);
                    tv_phonecancel.setVisibility(View.GONE);
                }
            }
        });
        ed_sq.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        ed_sq.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        ed_sq.setText(s);
                        ed_sq.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    ed_sq.setText(s);
                    ed_sq.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        ed_sq.setText(s.subSequence(0, 1));
                        ed_sq.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });
        showPopupWindow();
        showPopupWindowMem();
        showSettingPopupWindow();
    }

    //机型弹框
    private void showPopupWindow() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.jihao, null);
        popupWindow = new PopupWindow(contentview, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //popupWindow
//        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
//        popupWindow.getContentView().setFocusable(true); // 这个很重要
//        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    popupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        lv_jh = ViewHolder.get(contentview, R.id.lv_jh);
        popAdapter = new PopAdapter(this, poplist);
        lv_jh.setAdapter(popAdapter);
        lv_jh.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ischoice = 1;
                ed_jh.setText(poplist.get(position).SERIAL_NO);
                tv_modle.setText(poplist.get(position).MODEL_NAME);
                jixing = poplist.get(position).MODEL_ID;
                jihao = poplist.get(position).MACHINE_ID;
                ed_jh.clearFocus();
                popupWindow.dismiss();
                tv_cancel.setVisibility(View.VISIBLE);
                hideSoftInput(MainActivity.this, ed_jh);
            }
        });
    }

    //查询会员弹框
    private void showPopupWindowMem() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.huiyuan, null);
        MempopupWindow = new PopupWindow(contentview, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //popupWindow
//        popupWindow.setFocusable(true);
        MempopupWindow.setOutsideTouchable(true);
        MempopupWindow.setBackgroundDrawable(new BitmapDrawable());
//        popupWindow.getContentView().setFocusable(true); // 这个很重要
//        popupWindow.getContentView().setFocusableInTouchMode(true);
        MempopupWindow.getContentView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    MempopupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        lv_hy = ViewHolder.get(contentview, R.id.lv_hy);
        memAdapter = new MemAdapter(this, MemberList);
        lv_hy.setAdapter(memAdapter);
        lv_hy.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                isphonechoice =1;
                ed_yhmc.setText(MemberList.get(position).PHONE_NUMBER);
                tv_khmc.setText(MemberList.get(position).SALE_CUST_NAME);
                tv_phonecancel.setVisibility(View.VISIBLE);
                //客户ID
                saleCustId = MemberList.get(position).SALE_CUST_ID;
                comfirmtype = 1;
                ed_yhmc.clearFocus();
                MempopupWindow.dismiss();
                hideSoftInput(MainActivity.this, ed_yhmc);
                EventBus.getDefault().post(new MemEvent(MemberList.get(position).SALE_CUST_NAME));
            }
        });
    }

    //设置弹框
    private void showSettingPopupWindow() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.item_setting, null);
        settingpopupWindow = new PopupWindow(contentview, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //popupWindow
//        popupWindow.setFocusable(true);
        settingpopupWindow.setOutsideTouchable(true);
        settingpopupWindow.setBackgroundDrawable(new BitmapDrawable());
//        popupWindow.getContentView().setFocusable(true); // 这个很重要
//        popupWindow.getContentView().setFocusableInTouchMode(true);
        settingpopupWindow.getContentView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    settingpopupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        rl_warehouse = ViewHolder.get(contentview, R.id.rl_warehouse);
        rl_loginout = ViewHolder.get(contentview, R.id.rl_loginout);
        rl_warehouse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                settingpopupWindow.dismiss();
                showWareHouse();
            }
        });
        rl_loginout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                settingpopupWindow.dismiss();
                showLoginout();
            }
        });
    }

    private void setListenerFotEditText(View view) {
        SoftKeyboardStateHelper softKeyboardStateHelper = new SoftKeyboardStateHelper(view);
        softKeyboardStateHelper.addSoftKeyboardStateListener(new SoftKeyboardStateHelper.SoftKeyboardStateListener() {
            @Override
            public void onSoftKeyboardOpened(int keyboardHeightInPx) {
                //键盘打开
//                Toast.makeText(getApplicationContext(), "打开", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSoftKeyboardClosed() {
                //键盘关闭
                ed_shopid.clearFocus();
                ed_vipnumber.clearFocus();
                ed_sq.clearFocus();
//                ed_shopid.setText(null);
//                Toast.makeText(getApplicationContext(),  "关闭", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 扫码重复商品会添加在已有的商品中，不重复的新添加一条商品信息
     */
    private boolean goodContains(String shopid) {
        if (list.size() != 0) {
            for (int j = 0; j < list.size(); j++) {
                if (shopid.equals(list.get(j).ShopId)) {
                    int num = list.get(j).ShopNum;
                    list.get(j).ShopNum = num + 1;
                    list.get(j).ShopTotal = (num + 1) * convertToDouble(list.get(j).ShopSalePrice, 0.0f) + "";
                    saleAdapter.notifyDataSetChanged();
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 更新价格商品数量等
     */
    private void updateInfo(int i) {
        int shop_num = 0;
        double shop_total = 0.00;
        double shop_sale_total = 0.00;


        if (i != 0) {
            for (int j = 0; j < i; j++) {
                shop_num = shop_num + list.get(j).ShopNum;
                shop_sale_total = shop_sale_total + convertToDouble(list.get(j).ShopPrice, 0.0f) * list.get(j).ShopNum;
                shop_total = shop_total + convertToDouble(list.get(j).ShopTotal, 0.0f);
            }
            tv_shop_num.setText(shop_num + "");
            tv_yj.setText("￥" + DecimalUtil.round(shop_sale_total + "", 2));
            Total_yuanjia = DecimalUtil.round(shop_sale_total + "", 2);
            tv_total_money.setText("￥" + DecimalUtil.round(shop_total + "", 2));
            tv_hyj.setText("￥" + DecimalUtil.round(shop_total + "", 2));
            tv_zzjg.setText("￥" + DecimalUtil.round(shop_total + "", 2));
            zzjg = DecimalUtil.round(shop_total + "", 2) + "";
        } else {
            tv_shop_num.setText("0");
            tv_yj.setText("￥0.00");
            Total_yuanjia = BigDecimal.valueOf(0);
            tv_total_money.setText("￥0.00");
            tv_hyj.setText("￥0.00");
            tv_zzjg.setText("￥0.00");
        }
        EventBus.getDefault().post(new CustomerShopEvent(list));
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

    }

    /**
     * 隐藏键盘
     *
     * @param bas 上下文
     */
    public static void hideSoftInput(BaseActivity bas, EditText et) {
        try {

            ((InputMethodManager) bas.getSystemService(Context.INPUT_METHOD_SERVICE)).

                    hideSoftInputFromWindow(et.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 当触摸就会执行此方法
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        mScreensaver.resetTime(); //重置时间
        Log.i("lzx", "dispatchTouchEvent: " + "触摸就会执行此方法");
        EventBus.getDefault().post(new AdvEvent(2));
        return super.dispatchTouchEvent(ev);
    }

    //申请折扣
    public void getApplyInfo(String keyId) {
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        Log.i(TAG, "getMemberInfo: " + userID);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_GETSALE, userID
                , new RequestParams(this).getApplyParams(keyId)
                , this
                , false, 2);
    }

    //查询审核状态
    public void getStateInfo(String keyId) {
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        Log.i(TAG, "getMemberInfo: " + userID);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_STATE, userID
                , new RequestParams(this).getStateParams(keyId)
                , this
                , false, 7);
    }

    //根据机号获得机型
    public void getModelInfo(String serialNo) {
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        Log.i(TAG, "getMemberInfo: " + userID);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_LOCATIONJIHAO, userID
                , new RequestParams(this).getModelParams(serialNo)
                , this
                , false, 4);
    }

    //0状态保存订单
    public void getOrderInfo(String saleCustId, String vipNumber, String warehouseId
            , String createDate, String machineId, String modelId, String isDiscount, List<CustomerGoodsBean> list) {
//        List<String> partId, List<String> partNum, List<String> partSalePrice, List<String> partCat
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        String company_id = SharedPreferencesUtil.getString(this, ConstantsUtils.COMPANY_ID);
        String dept_id = SharedPreferencesUtil.getString(this, ConstantsUtils.DEPT_ID);
        Log.i(TAG, "getOrderInfo: " + company_id + "=======" + dept_id);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_LOCATION_ORDER, ""
                , new RequestParams(this).getZeroOrderParams(userID,saleCustId, vipNumber, warehouseId, company_id, dept_id
                        , createDate, machineId, modelId, isDiscount
                        , list)

                , this
                , false, 5);
//        partId, partNum, partSalePrice, partCat
    }


    //0状态保存订单
    public void getOrder2Info(String saleCustId, String vipNumber, String warehouseId
            , String createDate, String machineId, String modelId, String isDiscount, String discountRate,
                              List<CustomerGoodsBean> list) {
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        String company_id = SharedPreferencesUtil.getString(this, ConstantsUtils.COMPANY_ID);
        String dept_id = SharedPreferencesUtil.getString(this, ConstantsUtils.DEPT_ID);
        Log.i(TAG, "getOrder2Info: " + company_id + "=======" + dept_id);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_LOCATION_ORDER, ""
                , new RequestParams(this).getwoOneOrderParams(userID,saleCustId, vipNumber, warehouseId, company_id, dept_id
                        , createDate, machineId, modelId, isDiscount, discountRate
                        , list)
                , this
                , false, 5);

    }

    /**
     * 查询会员折扣
     */
    public void getSaleInfo(String vipNumber) {
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        Log.i(TAG, "getMemberInfo: " + userID);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_SALEINFO_URL, userID
                , new RequestParams(this).getSaleInfoParams(vipNumber)
                , this
                , false, 1);
    }

    /**
     * 查询会员信息
     */
    public void getMemInfo(String phone) {
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        Log.i(TAG, "getMemberInfo: " + userID);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_LOCATIONADMIN, userID
                , new RequestParams(this).getSearchMemberParams(phone)
                , this
                , false, 6);
    }

    //查看商品详情
    public void getShopInfo( String content) {
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        String compayID = SharedPreferencesUtil.getString(this, ConstantsUtils.COMPANY_ID);
        Log.i(TAG, "getShopInfo: "+compayID);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_LOCATIONMEUM, userID
                , new RequestParams(this).getShopParams(compayID, content)
                , this
                , false, 3);
    }

    /**
     * 当使用物理键盘就会执行此方法
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        mScreensaver.resetTime(); //重置时间
        EventBus.getDefault().post(new AdvEvent(2));
        if (event.getAction() != KeyEvent.ACTION_DOWN) {
            //不响应按键抬起时的动作
            return scanGun.isMaybeScanning(event.getKeyCode(), event);
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * base64解密
     */
    public static String getUidFromBase64(String base64Id) {
//        long uid = -1l;
        String result = "";
        if (!TextUtils.isEmpty(base64Id)) {
            result = new String(Base64.decode(base64Id.getBytes(), Base64.DEFAULT));
        }
        Log.d(TAG, "getUidFromBase64 uid = " + result);
        return result;
    }


    /**
     * 时间到就会执行此方法
     */
    @Override
    public void onTimeOut(Screensaver screensaver) {
        mScreensaver.stop();
        EventBus.getDefault().post(new AdvEvent(1));
    }


    @Override
    public void onDestroy() {

        super.onDestroy();
        mScreensaver.stop(); //停止计时
//        presentation.dismiss();

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mScreensaver.start();
        EventBus.getDefault().post(new AdvEvent(2));
    }

    @Override
    protected void onResume() {
        super.onResume();
        mScreensaver.start();
        EventBus.getDefault().post(new AdvEvent(2));
    }

    @Override
    protected void onPause() {
        super.onPause();
        mScreensaver.stop(); //停止计时
        EventBus.getDefault().post(new AdvEvent(2));
    }

    @Override
    public void onSuccess(String response, int flag) {
        try {
            if (flag == 1) {
                getMemberData(response);
            }
            if (flag == 2) {
                getApplyData(response);
            }
            if (flag == 3) {
                getShopData(response);
            }
            if (flag == 4) {
                getModelData(response);
            }
            if (flag == 5) {
                getOrderData(response);
            }
            if (flag == 6) {
                getMemIdData(response);
            }
            if (flag == 7) {
                getStateData(response);
            }
        } catch (Exception e) {
            GeneralUtil.tryShow(getApplicationContext(), e);
        }
    }

    private void getStateData(String response) {
        Log.i(TAG, "getMemIdData: " + response);
        String en = JsonUtil.getString(response, "en", "");
        String flag = JsonUtil.getString(en, "flag", "");
        if ("1".equals(flag)) {
            ManageStateInfo info = JSON.parseObject(en, ManageStateInfo.class);
            if ("1".equals(info.nodeInfoList.get(0).nodeState) && "1".equals(info.nodeInfoList.get(1).nodeState) && "1".equals(info.nodeInfoList.get(2).nodeState)) {
                tv_confirm_all.setText("确定");
                SaleScreensaver.stop();
                tv_zkl.setText(zhekou);
                String zzjg = DecimalUtil.strMul2(Total_yuanjia.toString(), DecimalUtil.round(zhekou + "", 2).toString(), 2);
                tv_zzjg.setText(zzjg);
                EventBus.getDefault().post(new ZkEvent(zhekou, zzjg));
                EventBus.getDefault().post(new AdvEvent(2));
                if (wattingDialog.isShowing()) {
                    wattingDialog.dismiss();
                }
//                SQDialog();
                show(commPartSaleId, partSaleNo, saleCustId, zzjg);
                Log.i(TAG, "getStateData: " + "折扣申请成功！");
                tv_confirm_all.setEnabled(true);

            } else {
                SaleScreensaver.resetTime();
                if (!wattingDialog.isShowing()) {
                    wattingDialog.show();
                }

                Log.i(TAG, "getStateData: " + "折扣申请中...请勿其他操作！");
                tv_confirm_all.setText("折扣申请中...请勿其他操作！");
                tv_confirm_all.setEnabled(false);
            }
        } else {
            ToastUtil.showToast(this, "查询审批状态失败，请重试！");
            tv_confirm_all.setEnabled(true);
        }
    }

    private void getMemIdData(String response) {


            ManageMemberInfo info = JSON.parseObject(response, ManageMemberInfo.class);
            if (info.list.size() == 0 || info.list == null) {
                ToastUtil.showToast(this, "会员不存在！");
                if (MempopupWindow.isShowing()) {
                    MempopupWindow.dismiss();
                }
            } else if(info.list.size() == 1){
                isphonechoice = 1;
                tv_phonecancel.setVisibility(View.VISIBLE);
                ed_yhmc.setText(info.list.get(0).PHONE_NUMBER);
                tv_khmc.setText(info.list.get(0).SALE_CUST_NAME);
                //客户ID
                saleCustId = info.list.get(0).SALE_CUST_ID;
                comfirmtype = 1;
                ed_yhmc.clearFocus();
                hideSoftInput(MainActivity.this, ed_yhmc);
                EventBus.getDefault().post(new MemEvent(info.list.get(0).SALE_CUST_NAME));
            }
            else if (info.list.size() > 1) {
                MemberList.clear();
                MemberList.addAll(info.list);
                memAdapter.notifyDataSetChanged();
                MempopupWindow.showAsDropDown(ed_yhmc, 0, 0);
            }
        }
//        else {
//            ToastUtil.showToast(this, "会员不存在！");
//            if (MempopupWindow.isShowing()) {
//                MempopupWindow.dismiss();
//            }
//        }
//    }

    private void getOrderData(String response) {
        Log.i(TAG, "getOrderData: " + response);
        String code = JsonUtil.getString(response, "code", "");
        if ("200".equals(code)){
            //订单ID
            commPartSaleId = JsonUtil.getString(response, "PART_SALE_LIST_ID", "");
            //订单No
            partSaleNo = JsonUtil.getString(response, "PART_SALE_LIST_NO", "");
            getApplyInfo(commPartSaleId);
        }else {
            ToastUtil.showToast(this, "提交订单失败！请重试");
            tv_confirm_all.setEnabled(true);
        }
//        String flag = JsonUtil.getString(en, "flag", "");
//        if ("1".equals(flag)) {
//            String isDiscount = JsonUtil.getString(en, "isDiscount", "");
//            //订单No
//            partSaleNo = JsonUtil.getString(en, "partSaleNo", "");
//            //订单ID
//            commPartSaleId = JsonUtil.getString(en, "PART_SALE_LIST_ID", "");
//            getApplyInfo(commPartSaleId);
//        } else {
//            ToastUtil.showToast(this, "提交订单失败！请重试");
//            tv_confirm_all.setEnabled(true);
//        }


    }

    private void getModelData(String response) {

            ManageModleInfo info = JSON.parseObject(response, ManageModleInfo.class);
            if (info.list.size() == 0 || info.list == null) {
                ToastUtil.showToast(this, "机号不存在！");
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            } else if (info.list.size() == 1) {
                ischoice = 1;
                ed_jh.setText(info.list.get(0).SERIAL_NO);
                tv_modle.setText(info.list.get(0).MODEL_NAME);
                jixing = info.list.get(0).MODEL_ID;
                jihao = info.list.get(0).MACHINE_ID;
                ed_jh.clearFocus();
                popupWindow.dismiss();
                tv_cancel.setVisibility(View.VISIBLE);
                hideSoftInput(MainActivity.this, ed_jh);
            } else if (info.list.size() > 1) {
                poplist.clear();
                poplist.addAll(info.list);
                popAdapter.notifyDataSetChanged();
                popupWindow.showAsDropDown(rl_jh, -20, 0);
            }
        }
//        else {
//            ToastUtil.showToast(this, "机号不存在！");
//            if (popupWindow.isShowing()) {
//                popupWindow.dismiss();
//            }
//        }
//    }

    private void getApplyData(String response) {
        Log.i(TAG, "getApplyData: " + response);
        String en = JsonUtil.getString(response, "en", "");
        String flag = JsonUtil.getString(en, "flag", "");
        if ("1".equals(flag)) {
            if (zktype == 0) {
                show(commPartSaleId, partSaleNo, saleCustId, zzjg);
                ToastUtil.showToast(this, "提交订单成功！");
            } else {
                zhekou = ed_sq.getText().toString().trim();
                getStateInfo(commPartSaleId);
                SaleScreensaver.start();
            }
        } else {
            ToastUtil.showToast(this, "提交审批失败，请重新提交！");
            tv_confirm_all.setEnabled(true);
        }
    }

    private void getShopData(String response) {
        CustomerGoodsBean bean = new CustomerGoodsBean();
        tv_confirm.setEnabled(true);
        ManageGoodInfo info = JSON.parseObject(response, ManageGoodInfo.class);
        if (info.list.size() == 0 || info.list == null) {
            ToastUtil.showToast(this, "商品不存在，请联系管理员添加！");
            tv_confirm.setEnabled(true);
        } else if (info.list.size() == 1) {
            bean.ShopsysId = info.list.get(0).PART_ID;
            bean.ShopId = info.list.get(0).PART_NO;
            bean.ShopName = info.list.get(0).PART_NAME;
            bean.ShopDiscount = info.list.get(0).PART_CAT;
            bean.ShopNum = 1;
            if (comfirmtype == 0 || comfirmtype == 1) {
                bean.ShopPrice = info.list.get(0).SALE_PRICE;
                bean.ShopSalePrice = bean.ShopPrice;
                bean.ShopMemberPrice = bean.ShopPrice;
                bean.ShopTotal = bean.ShopPrice;
            } else {
                if ("1".equals(info.list.get(0).PART_CAT)) {
                    bean.ShopPrice = info.list.get(0).SALE_PRICE;
                    bean.ShopSalePrice = convertToDouble(info.list.get(0).SALE_PRICE, 0.00) * commonPartDiscount + "";
                    bean.ShopMemberPrice = bean.ShopSalePrice;
                    bean.ShopTotal = bean.ShopPrice;
                } else {
                    bean.ShopPrice = info.list.get(0).SALE_PRICE;
                    bean.ShopSalePrice = convertToDouble(info.list.get(0).SALE_PRICE, 0.00) * performancePartDiscount + "";
                    bean.ShopMemberPrice = bean.ShopSalePrice;
                    bean.ShopTotal = bean.ShopPrice;
                }
            }
            if (!goodContains(bean.ShopId)) {
                list.add(bean);
                saleAdapter.notifyDataSetChanged();
            }
            updateInfo(list.size());
            tv_confirm.setEnabled(true);
        } else {
            shopOrderDialog = new ShopOrderDialog(this, shopid, comfirmtype, commonPartDiscount, performancePartDiscount, R.style.MyDialogStyle, new BaseDialog.LeaveMyDialogListener() {
                @Override
                public void onClick(View view) {

                }
            });
            shopOrderDialog.setCanceledOnTouchOutside(true);
            shopOrderDialog.show();
            tv_confirm.setEnabled(true);
        }

    }

    //获取会员折扣
    private void getMemberData(String response) {
        Log.i(TAG, "getMemberData: " + response);
        String en = JsonUtil.getString(response, "en", "");
        String flag = JsonUtil.getString(en, "flag", "");
        if ("1".equals(flag)) {
            ed_vipnumber.clearFocus();
            hideSoftInput(MainActivity.this, ed_vipnumber);
            comfirmtype = 2;
            String info = JsonUtil.getString(en, "info", "");
            String userName = JsonUtil.getString(info, "userName", "");
            tv_hyid.setText(vipnumber);
            EventBus.getDefault().post(new MemIdEvent(vipnumber));
            performancePartDiscount = convertToDouble(JsonUtil.getString(info, "performancePartDiscount", ""), 0.00);
            commonPartDiscount = convertToDouble(JsonUtil.getString(info, "commonPartDiscount", ""), 0.00);
            ll_hyzk.setVisibility(View.VISIBLE);
            tv_cy.setText("常用折扣："+commonPartDiscount);
            tv_xn.setText("性能折扣："+performancePartDiscount);
            if (list.size() != 0) {
                for (int j = 0; j < list.size(); j++) {
                    if ("1".equals(list.get(j).ShopDiscount)) {
                        list.get(j).ShopSalePrice = convertToDouble(list.get(j).ShopPrice, 0.00) * commonPartDiscount + "";
                        list.get(j).ShopMemberPrice = convertToDouble(list.get(j).ShopPrice, 0.00) * commonPartDiscount + "";
                        list.get(j).ShopTotal = convertToDouble(list.get(j).ShopPrice, 0.00) * commonPartDiscount * list.get(j).ShopNum + "";
                    } else {
                        list.get(j).ShopSalePrice = convertToDouble(list.get(j).ShopPrice, 0.00) * performancePartDiscount + "";
                        list.get(j).ShopMemberPrice = convertToDouble(list.get(j).ShopPrice, 0.00) * performancePartDiscount + "";
                        list.get(j).ShopTotal = convertToDouble(list.get(j).ShopPrice, 0.00) * performancePartDiscount * list.get(j).ShopNum + "";
                    }
                }
                saleAdapter.notifyDataSetChanged();
                updateInfo(list.size());
            }

        } else {
            comfirmtype = 1;
            ll_hyzk.setVisibility(View.GONE);
            ToastUtil.showToast(this, "会员ID不存在！请重新输入");
        }

    }

    @Override
    public void onFailure(Request request, IOException e, int flag) {
        if (flag == 5){
            tv_confirm_all.setEnabled(true);
            Log.i(TAG, "onFailure: tv_confirm_all");
        }
        if (flag == 3){
            tv_confirm.setEnabled(true);
        }


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //获取会员折扣
            case R.id.tv_searchmenbr:
                vipnumber = ed_vipnumber.getText().toString().trim();
                if (comfirmtype != 0) {
                    if (!TextUtils.isEmpty(vipnumber)) {
                        getSaleInfo(vipnumber);
                    } else {
                        ToastUtil.showToast(this, "请输入客户会员ID");
                    }
                } else {
                    ToastUtil.showToast(this, "请查询会员信息后，再查看会员折扣！");
                }
                break;
            case R.id.tv_confirm:
                shopid = ed_shopid.getText().toString().trim();
                if (TextUtils.isEmpty(shopid) || "请输入/扫描商品二维码".equals(shopid)) {
                    ToastUtil.showToast(this, "请输入商品号码！");
//                    ed_shopid.setText(null);
                } else {
                    getShopInfo(shopid);
//                    ed_shopid.setText(null);
                    tv_confirm.setEnabled(false);
                }
                break;
            case R.id.tv_confirm_all:

                if (comfirmtype == 1) {

                    String ZK = ed_sq.getText().toString().trim();
                    if (TextUtils.isEmpty(jixing)) {
                        ToastUtil.showToast(this, "请获取机型");
                        return;
                    }
                    if (TextUtils.isEmpty(jihao)) {
                        ToastUtil.showToast(this, "请获取机号");
                        return;
                    }
                    if (TextUtils.isEmpty(saleCustId)) {
                        ToastUtil.showToast(this, "当前客户ID不存在，请重新输入客户名称");
                        return;
                    }
                    String WareHouseId = SharedPreferencesUtil.getString(this, ConstantsUtils.WAREHOUSE_ID);
                    if (TextUtils.isEmpty(WareHouseId)) {
                        ToastUtil.showToast(this, "仓库号为空，请先设置仓库号！");
                        return;
                    }
                    if (list.size()==0){
                        ToastUtil.showToast(this, "请加入商品！");
                        return;
                    }
//                    List<String> partId = new ArrayList<>();
//                    List<String> partNum = new ArrayList<>();
//                    List<String> partSalePrice = new ArrayList<>();
//                    List<String> partCat = new ArrayList<>();
//                    if (list.size() > 0) {
//                        for (int j = 0; j < list.size(); j++) {
//                            partId.add(list.get(j).ShopsysId);
//                            partNum.add(list.get(j).ShopNum + "");
//                            partSalePrice.add(list.get(j).ShopPrice);
//                            partCat.add(list.get(j).ShopDiscount);
//                        }
//                    } else {
//                        ToastUtil.showToast(this, "请加入商品！");
//                        return;
//                    }
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
                    //获取当前时间
                    Date date = new Date(System.currentTimeMillis());
                    if (zktype == 0) {

                        getOrderInfo(saleCustId, "", WareHouseId, simpleDateFormat.format(date).toString(), jihao, jixing, "0", list);
                        tv_confirm_all.setEnabled(false);
                    } else {
                        if (TextUtils.isEmpty(ZK)) {
                            ToastUtil.showToast(this, "请输入申请的折扣！");
                            return;
                        }
                        getOrder2Info(saleCustId, "", WareHouseId, simpleDateFormat.format(date).toString(), jihao, jixing, "1", ZK, list);
                        tv_confirm_all.setEnabled(false);
                    }
                } else if (comfirmtype == 0) {
                    ToastUtil.showToast(this, "查询会员，才能提交订单！");
                    tv_confirm_all.setEnabled(true);
                } else {
                    String ZK = ed_sq.getText().toString().trim();
                    if (TextUtils.isEmpty(jixing)) {
                        ToastUtil.showToast(this, "请获取机型");
                        return;
                    }
                    if (TextUtils.isEmpty(jihao)) {
                        ToastUtil.showToast(this, "请获取机号");
                        return;
                    }
                    if (TextUtils.isEmpty(saleCustId)) {
                        ToastUtil.showToast(this, "当前客户ID不存在，请重新输入客户名称");
                        return;
                    }
                    String WareHouseId = SharedPreferencesUtil.getString(this, ConstantsUtils.WAREHOUSE_ID);
                    if (TextUtils.isEmpty(WareHouseId)) {
                        ToastUtil.showToast(this, "仓库号为空，请先设置仓库号！");
                        return;
                    }
                    if (list.size()==0){
                        ToastUtil.showToast(this, "请加入商品！");
                        return;
                    }
//                    List<String> partId = new ArrayList<>();
//                    List<String> partNum = new ArrayList<>();
//                    List<String> partSalePrice = new ArrayList<>();
//                    List<String> partCat = new ArrayList<>();
//                    if (list.size() > 0) {
//                        for (int j = 0; j < list.size(); j++) {
//                            partId.add(list.get(j).ShopsysId);
//                            partNum.add(list.get(j).ShopNum + "");
//                            partSalePrice.add(list.get(j).ShopPrice);
//                            partCat.add(list.get(j).ShopDiscount);
//                        }
//                    } else {
//                        ToastUtil.showToast(this, "请加入商品！");
//                        return;
//                    }
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
                    //获取当前时间
                    Date date = new Date(System.currentTimeMillis());
                    if (zktype == 0) {
                        getOrderInfo(saleCustId, vipnumber, WareHouseId, simpleDateFormat.format(date).toString(), jihao, jixing, "2", list);
                        tv_confirm_all.setEnabled(false);
                    } else {
                        if (TextUtils.isEmpty(ZK)) {
                            ToastUtil.showToast(this, "请输入申请的折扣！");
                            return;
                        }
                        getOrder2Info(saleCustId, vipnumber, WareHouseId, simpleDateFormat.format(date).toString(), jihao, jixing, "1", ZK, list);
//                        partId, partNum, partSalePrice, partCat
                        tv_confirm_all.setEnabled(false);
                    }

                }
                break;
            case R.id.ckb:
                if (ckb.isChecked()) {
                    ckb.setChecked(true);
                    ed_sq.setEnabled(true);
                    rl_zkl.setVisibility(View.VISIBLE);
                    EventBus.getDefault().post(new ZklEvent(1));
                    zktype = 1;
                } else {
                    ckb.setChecked(false);
                    ed_sq.setEnabled(false);
                    rl_zkl.setVisibility(View.GONE);
                    EventBus.getDefault().post(new ZklEvent(0));
                    zktype = 0;
                }
                break;

            case R.id.tv_cancel:
                ischoice = 0;
                ed_jh.setText(null);
                tv_modle.setText(null);
                tv_cancel.setVisibility(View.GONE);
                break;
            case R.id.iv_settings:
                settingpopupWindow.showAsDropDown(iv_settings, 0, 0);
                break;

            case R.id.tv_list:
                startActivity(new Intent(this, UnpaidActivity.class));
                break;
            case R.id.tv_dj:
                startActivity(new Intent(this, EatnestActivity.class));
                break;
            case R.id.tv_phonecancel:
                isphonechoice = 0;
                ed_yhmc.setText(null);
                tv_khmc.setText("暂未获取");
                tv_phonecancel.setVisibility(View.GONE);
                break;

            default:
                break;
        }
    }

    @Override
    public void linster(final int position, int flag) {
        if (flag == 1) {
            int num = list.get(position).ShopNum;
            if (num == 1) {
                list.remove(position);
                saleAdapter.notifyDataSetChanged();

            } else {
                list.get(position).ShopNum = num - 1;
                list.get(position).ShopTotal = (num - 1) * convertToDouble(list.get(position).ShopSalePrice, 0.0f) + "";
                saleAdapter.notifyDataSetChanged();

            }
            updateInfo(list.size());
        }
        if (flag == 2) {
            int num = list.get(position).ShopNum;
            list.get(position).ShopNum = num + 1;
            list.get(position).ShopTotal = (num + 1) * convertToDouble(list.get(position).ShopSalePrice, 0.0f) + "";
            saleAdapter.notifyDataSetChanged();
            updateInfo(list.size());
        }
        if (flag == 3) {
            comfirmOrderDialog = new ComfirmOrderDialog(this, "修改商品数量", R.style.MyDialogStyle, new BaseDialog.LeaveMyDialogListener() {

                @Override
                public void onClick(View view) {
                    EditText ed_bz = comfirmOrderDialog.findViewById(R.id.ed_bz);
                    //隐藏输入法
                    InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    switch (view.getId()) {

                        case R.id.bt_quit_qx:
                            comfirmOrderDialog.dismiss();

                            manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                            break;
                        case R.id.bt_quit_ok:
                            comfirmOrderDialog.dismiss();
                            String num = ed_bz.getText().toString().trim();
                            if (null == num || "0".equals(num) || "".equals(num)) {
                                Toast.makeText(getApplicationContext(), "输入的数量不能为0，或者空", Toast.LENGTH_SHORT).show();
                                return;
                            } else {
                                list.get(position).ShopNum = Integer.parseInt(num);
                                list.get(position).ShopTotal = Integer.parseInt(num) * convertToDouble(list.get(position).ShopSalePrice, 0.0f) + "";
                                saleAdapter.notifyDataSetChanged();
                                updateInfo(list.size());
                            }

                            manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                            break;

                        default:

                            manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                            break;
                    }
                }
            });
            comfirmOrderDialog.setCanceledOnTouchOutside(false);
            comfirmOrderDialog.show();
        }
    }

    //把String转化为double
    public static double convertToDouble(String number, double defaultValue) {
        if (TextUtils.isEmpty(number)) {
            return defaultValue;
        }
        try {
            return Double.parseDouble(number);
        } catch (Exception e) {
            return defaultValue;
        }

    }

    @Override
    @Subscribe
    public void onEventMainThread(BaseEvent event) throws IOException {
        super.onEventMainThread(event);
        if (event instanceof ShopEvent) {
            shopOrderDialog.dismiss();
            CustomerGoodsBean bean = ((ShopEvent) event).getBean();
            if (!goodContains(bean.ShopId)) {
                list.add(bean);
                saleAdapter.notifyDataSetChanged();
            }
            updateInfo(list.size());
        }
        if (event instanceof PaystatrEvent) {
            if (((PaystatrEvent) event).getType()==1){
                zktype = 0;
                comfirmtype = 0;
                jixing = "";
                jihao = "";
                saleCustId = "";
                ed_jh.setText(null);
                tv_modle.setText(null);
                tv_khmc.setText("暂未获取");
                tv_hyid.setText("暂未获取");
                ed_yhmc.setText(null);
                ed_vipnumber.setText(null);
                tv_zkl.setText("1.00");
                ckb.setChecked(false);
                rl_zkl.setVisibility(View.GONE);
                ed_sq.setText(null);
                ed_shopid.setText(null);
                ed_sq.setEnabled(false);
                tv_cancel.setVisibility(View.GONE);
                tv_phonecancel.setVisibility(View.GONE);
                ll_hyzk.setVisibility(View.GONE);
                list.clear();
                saleAdapter.notifyDataSetChanged();
                updateInfo(list.size());
                EventBus.getDefault().post(new MemEvent("暂未获取"));
                EventBus.getDefault().post(new MemIdEvent("暂未获取"));
                EventBus.getDefault().post(new ZkEvent("1.00", "￥0.00"));
                EventBus.getDefault().post(new ZklEvent(0));
                tv_confirm_all.setEnabled(true);
                ToastUtil.showToast(getApplicationContext(), "订单支付成功！", 3000);
                EventBus.getDefault().post(new PaySEvent(1));
            }
        }
    }

//    private void SQDialog() {
//        comfirmDialog = new ComfirmDialog(this, "提示", "申请折扣成功!", R.style.MyDialogStyle, new BaseDialog.LeaveMyDialogListener() {
//
//            @Override
//            public void onClick(View view) {
//                switch (view.getId()) {
//
//                    case R.id.bt_quit_qx:
//                        comfirmDialog.dismiss();
//                        zktype = 0;
//                        comfirmtype = 0;
//                        jixing = "";
//                        jihao = "";
//                        saleCustId = "";
//                        ed_jh.setText(null);
//                        tv_modle.setText(null);
//                        tv_khmc.setText("暂未获取");
//                        tv_hyid.setText("暂未获取");
//                        ed_yhmc.setText(null);
//                        ed_vipnumber.setText(null);
//                        tv_zkl.setText("1.00");
//                        ckb.setChecked(false);
//                        rl_zkl.setVisibility(View.GONE);
//                        ed_sq.setText(null);
//                        ed_sq.setEnabled(false);
//                        tv_cancel.setVisibility(View.GONE);
//                        tv_phonecancel.setVisibility(View.GONE);
//                        list.clear();
//                        saleAdapter.notifyDataSetChanged();
//                        updateInfo(list.size());
//                        EventBus.getDefault().post(new MemEvent("暂未获取"));
//                        EventBus.getDefault().post(new MemIdEvent("暂未获取"));
//                        EventBus.getDefault().post(new ZkEvent("1.00", "￥0.00"));
//                        EventBus.getDefault().post(new ZklEvent(0));
//                        tv_confirm_all.setEnabled(true);
//                        break;
//                    case R.id.bt_quit_ok:
//                        comfirmDialog.dismiss();
//                        zktype = 0;
//                        comfirmtype = 0;
//                        jixing = "";
//                        jihao = "";
//                        saleCustId = "";
//                        ed_jh.setText(null);
//                        tv_modle.setText(null);
//                        tv_khmc.setText("暂未获取");
//                        tv_hyid.setText("暂未获取");
//                        ed_yhmc.setText(null);
//                        ed_vipnumber.setText(null);
//                        tv_zkl.setText("1.00");
//                        ckb.setChecked(false);
//                        rl_zkl.setVisibility(View.GONE);
//                        tv_cancel.setVisibility(View.GONE);
//                        tv_phonecancel.setVisibility(View.GONE);
//                        ed_sq.setText(null);
//                        ed_sq.setEnabled(false);
//                        list.clear();
//                        saleAdapter.notifyDataSetChanged();
//                        updateInfo(list.size());
//                        EventBus.getDefault().post(new MemEvent("暂未获取"));
//                        EventBus.getDefault().post(new MemIdEvent("暂未获取"));
//                        EventBus.getDefault().post(new ZkEvent("1.00", "￥0.00"));
//                        EventBus.getDefault().post(new ZklEvent(0));
//                        tv_confirm_all.setEnabled(true);
//                        break;
//
//                    default:
//                        zktype = 0;
//                        comfirmtype = 0;
//                        jixing = "";
//                        jihao = "";
//                        saleCustId = "";
//                        ed_jh.setText(null);
//                        tv_modle.setText(null);
//                        tv_khmc.setText("暂未获取");
//                        tv_hyid.setText("暂未获取");
//                        tv_zkl.setText("1.00");
//                        ckb.setChecked(false);
//                        rl_zkl.setVisibility(View.GONE);
//                        tv_cancel.setVisibility(View.GONE);
//                        tv_phonecancel.setVisibility(View.GONE);
//                        ed_sq.setEnabled(false);
//                        ed_sq.setText(null);
//                        ed_yhmc.setText(null);
//                        ed_vipnumber.setText(null);
//                        list.clear();
//                        saleAdapter.notifyDataSetChanged();
//                        updateInfo(list.size());
//                        EventBus.getDefault().post(new MemEvent("暂未获取"));
//                        EventBus.getDefault().post(new MemIdEvent("暂未获取"));
//                        EventBus.getDefault().post(new ZkEvent("1.00", "￥0.00"));
//                        EventBus.getDefault().post(new ZklEvent(0));
//                        tv_confirm_all.setEnabled(true);
//                        break;
//                }
//            }
//        });
//        comfirmDialog.setCanceledOnTouchOutside(false);
//        comfirmDialog.show();
//    }

    private void show(String order_id, String partno, String cus_id, String money) {
        comfirmPayDialog = new ComfirmPayDialog(this, order_id, partno, cus_id, money, R.style.MyDialogStyle, new BaseDialog.LeaveMyDialogListener() {

            @Override
            public void onClick(View view) {
                switch (view.getId()) {

                    case R.id.tv_close:
                        comfirmPayDialog.dismiss();
                        zktype = 0;
                        comfirmtype = 0;
                        jixing = "";
                        jihao = "";
                        saleCustId = "";
                        ed_jh.setText(null);
                        tv_modle.setText(null);
                        tv_khmc.setText("暂未获取");
                        tv_hyid.setText("暂未获取");
                        ed_yhmc.setText(null);
                        ed_vipnumber.setText(null);
                        ed_shopid.setText(null);
                        tv_zkl.setText("1.00");
                        ckb.setChecked(false);
                        rl_zkl.setVisibility(View.GONE);
                        ed_sq.setText(null);
                        ed_sq.setEnabled(false);
                        tv_cancel.setVisibility(View.GONE);
                        tv_phonecancel.setVisibility(View.GONE);
                        ll_hyzk.setVisibility(View.GONE);
                        list.clear();
                        saleAdapter.notifyDataSetChanged();
                        updateInfo(list.size());
                        EventBus.getDefault().post(new MemEvent("暂未获取"));
                        EventBus.getDefault().post(new MemIdEvent("暂未获取"));
                        EventBus.getDefault().post(new ZkEvent("1.00", "￥0.00"));
                        EventBus.getDefault().post(new ZklEvent(0));
                        tv_confirm_all.setEnabled(true);
                        ToastUtil.showToast(getApplicationContext(), "订单尚未支付，请到未支付订单列表中中查看/支付", 3000);
                        break;
                    default:
                        break;
                }

            }

        });

        comfirmPayDialog.show();
    }

    private void showwatting() {
        wattingDialog = new WattingDialog(this, "提示", "折扣申请中...请勿其他操作！", R.style.MyDialogStyle, new BaseDialog.LeaveMyDialogListener() {

            @Override
            public void onClick(View view) {


            }

        });


    }

    private void showLoginout() {
        outcomfirmDialog = new ComfirmDialog(this, "提示", "是否确认退出当前账号", R.style.MyDialogStyle, new BaseDialog.LeaveMyDialogListener() {

            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.bt_quit_qx:
                        outcomfirmDialog.dismiss();
                        break;
                    case R.id.bt_quit_ok:

                        zktype = 0;
                        comfirmtype = 0;
                        jixing = "";
                        jihao = "";
                        saleCustId = "";
                        ed_jh.setText(null);
                        tv_modle.setText(null);
                        tv_khmc.setText("暂未获取");
                        tv_hyid.setText("暂未获取");
                        ed_yhmc.setText(null);
                        ed_vipnumber.setText(null);
                        ed_shopid.setText(null);
                        tv_zkl.setText("1.00");
                        ckb.setChecked(false);
                        rl_zkl.setVisibility(View.GONE);
                        tv_cancel.setVisibility(View.GONE);
                        tv_phonecancel.setVisibility(View.GONE);
                        ll_hyzk.setVisibility(View.GONE);
                        ed_sq.setText(null);
                        ed_sq.setEnabled(false);
                        zktype = 0;
                        list.clear();
                        saleAdapter.notifyDataSetChanged();
                        updateInfo(list.size());
                        EventBus.getDefault().post(new MemEvent("暂未获取"));
                        EventBus.getDefault().post(new MemIdEvent("暂未获取"));
                        EventBus.getDefault().post(new ZkEvent("1.00", "￥0.00"));
                        EventBus.getDefault().post(new ZklEvent(0));
                        tv_confirm_all.setEnabled(true);
                        SharedPreferencesUtil.putString(getApplicationContext(), ConstantsUtils.WAREHOUSE_ID, "");
                        SharedPreferencesUtil.putString(getApplicationContext(), ConstantsUtils.USER_ID, "");
                        SharedPreferencesUtil.putString(getApplicationContext(), ConstantsUtils.COMPANY_ID, "");
                        SharedPreferencesUtil.putString(getApplicationContext(), ConstantsUtils.DEPT_ID, "");
                        SharedPreferencesUtil.putBoolean(getApplicationContext(), ConstantsUtils.IS_LOGIN, false);
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        finish();
                        outcomfirmDialog.dismiss();
                        break;
                    default:
                        break;
                }
            }
        });
        outcomfirmDialog.setCanceledOnTouchOutside(false);
        outcomfirmDialog.show();
    }

    private void showWareHouse() {
        wareHouseDialog = new WareHouseDialog(this, "设置或修改仓库号", R.style.MyDialogStyle, new BaseDialog.LeaveMyDialogListener() {

            @Override
            public void onClick(View view) {
                EditText ed_bz = wareHouseDialog.findViewById(R.id.ed_bz);
                //隐藏输入法
                InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                switch (view.getId()) {

                    case R.id.bt_quit_qx:
                        wareHouseDialog.dismiss();


                        break;
                    case R.id.bt_quit_ok:
                        wareHouseDialog.dismiss();
                        String num = ed_bz.getText().toString().trim();
                        if ( "".equals(num)||"请输入您新的仓库号".equals(num)) {
                            Toast.makeText(getApplicationContext(), "输入仓库号不能为空", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            SharedPreferencesUtil.putString(getApplicationContext(), ConstantsUtils.WAREHOUSE_ID, num);
                        }
                        break;

                    default:

                        break;
                }
            }
        });
        wareHouseDialog.setCanceledOnTouchOutside(false);
        wareHouseDialog.show();
    }

}
